using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using AmazonCommon.Amazon.ECS;
using System.Text;
using AmazonCommon;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using DDNY.WebPortals.Common;
using Google.GData.YouTube;

namespace AmazonVer3.Controllers
{

    public class ProductController : ApplicationController
    {
        //
        // GET: /Product/


        public ActionResult List(string id, string sortby, string page)
        {
            string[] idItems = id.Split(new char[] { '-' });
            string nodeid = idItems[idItems.GetLength(0) - 2];
            List<string> browseNodeNames = new List<string>();
            for (int i = 0; i < idItems.GetLength(0); i++)
            {
                if (i % 2 == 1)
                {
                    browseNodeNames.Add(idItems[i]);
                }

            }
            ViewData[VDConstants.PageTitle] = GenerateTitleFromBrowseNodeNames(browseNodeNames, sortby, page);

            string searchIndex = idItems[1];
            BrowseNode[] childNodes = AmazonHelper.GetChildBrowseNodes(nodeid);

            List<SortValue> sortValues = PortalHelper.GetSortValuesBySearchIndex(searchIndex);
            ViewData[VDConstants.SortValues] = sortValues;


            ViewData[VDConstants.ChildBrowseNodes] = childNodes;
            ViewData[VDConstants.CurrentProductListActionId] = id;
            //TODO extract all Viewdata keys to constants
            ViewData[VDConstants.CurrentProductsPage] = page;
            ViewData[VDConstants.ProductsSortBy] = sortby;
            Items products = AmazonHelper.GetProductsForNode(nodeid, searchIndex, sortby, page);

            if (products.Item == null)
            {
                ViewData[VDConstants.ShouldIndex] = "NOINDEX";
                AddMetaTags();
            }

            //Items topsellers = AmazonHelper.GetTopSellersForNode(nodeid, searchIndex);
            //if (topsellers != null)
            //{
            //    ViewData[VDConstants.RightProductsList] = topsellers;
            //}

            AddRssLinkForTopSellers(nodeid, searchIndex);

            return View("ListByNode", products);


        }

        private void AddRssLinkForTopSellers(string nodeid, string searchIndex)
        {
            HtmlLink rss = new HtmlLink();
            rss.Href = "/Feed/TopSellers/" + nodeid + "-" + searchIndex;
            rss.Attributes["type"] = "application/rss+xml";
            rss.Attributes["rel"] = "alternate";
            rss.Attributes["title"] = "Top Sellers in this Category";
            ViewData[VDConstants.TopSellersFeedUrl] = HtmlUtil.RenderControl(rss);
        }

        [AcceptVerbs(new string[] { "Post", "Get" })]
        public ActionResult Search(string id)
        {
            Items products = AmazonHelper.GetProductsForKeyWord(id);
            return View("ListByNode", products);
        }


        public ActionResult ShowProductDetails(string id)
        {
            string[] idAndTitle = id.Split(new char[] { '-' });

            Item product = AmazonHelper.GetProductDetail(idAndTitle[0]);

            //if (product==null)
            //{
            //   throw new NullReferenceException();
            //}   


            ViewData[VDConstants.PageTitle] = GenerateTitleFromProductDetails(product);

            ViewData[VDConstants.CurrentASIN] = product.ASIN;
            SetCanonicalUrl(product);

            if (product.ItemAttributes != null && product.ItemAttributes.Title != null)
            {
                YouTubeFeed movieFeed = YoutubeHelper.FindVideoByKeyWord(product.ItemAttributes.Title);
                if (movieFeed.Entries != null && movieFeed.Entries.Count > 0)
                {
                    YouTubeEntry entry = movieFeed.Entries[0] as YouTubeEntry;
                    ViewData[VDConstants.SingleVideoPlayer] = string.Format(ComplexStrings.YouTubeSmallSize, entry.Media.VideoId.Value);
                }
            }

            ViewData[VDConstants.SimilarItems] = product.SimilarProducts;

            return View("ProductDetails", product);


        }

        private void SetCanonicalUrl(Item product)
        {

            HtmlLink canonical = new HtmlLink();
            canonical.Href = "/Product/ShowProductDetails/" + product.ASIN;
            canonical.Attributes["rel"] = "canonical";

            ViewData[VDConstants.CanonicalUrlLink] = HtmlUtil.RenderControl(canonical);

        }

        private object GenerateTitleFromProductDetails(Item product)
        {
            StringBuilder result = new StringBuilder();
            result.Append("Buy ");
            result.Append(product.ItemAttributes.Title);
            if (product.OfferSummary != null)
            {
                if (product.OfferSummary.LowestNewPrice != null)
                {
                    result.Append("| Prices from ");
                    result.Append(product.OfferSummary.LowestNewPrice.FormattedPrice);
                }
            }


            return result.ToString();
        }

        private string GenerateTitleFromBrowseNodeNames(List<string> nodeNames, string sortby, string page)
        {
            StringBuilder title = new StringBuilder();
            title.Append(ViewData[VDConstants.PageTitlePrefix]);           
            for (int i = nodeNames.Count - 1; i >= 0; i--)
            {
                string item = nodeNames[i];
                title.Append(" - ");
                title.Append(item);
            }
            if (nodeNames.Count == 0)
            {
                title.Append("Browse Categories");
            }

            if (!string.IsNullOrEmpty(sortby))
            {
                title.Append(" - Ordered By " + sortby);
            }

            if (!string.IsNullOrEmpty(page))
            {
                title.Append(" - Page " + page);
            }
            return title.ToString();
        }

        //public object Detail(string ASIN)
        //{
        //    //return View("Detail", service.GetProductById(id));
        //}



    }
}
